package com.example.demo.service.impl;

import com.example.demo.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author
 * @Description
 */
@Component
public class RedisServiceImpl implements RedisService {

    private static final Logger log = LoggerFactory.getLogger(RedisServiceImpl.class);
    @Resource
    private RedisTemplate<String, Map<Object, Object>> redisTemplate;

    @Override
    public boolean add(String key, Map<Object, Object> value) {
        redisTemplate.boundValueOps(key).set(value);
        Boolean expire = redisTemplate.expire(key, 60 * 3, TimeUnit.SECONDS);
        return expire == null || expire;
    }

    @Override
    public boolean remove(String key) {
        Boolean delete = redisTemplate.delete(key);
        return delete == null || delete;
    }

    @Override
    public Map<Object, Object> findByKey(String key) {
        Map<Object, Object> map = redisTemplate.boundValueOps(key).get();
        Long time = redisTemplate.opsForValue().getOperations().getExpire(key);
        log.debug("find剩余时间{}s", time);
        return map;
    }

    @Override
    public boolean updateTimeByKey(String key, long time) {
        // 获得剩余过期时间 默认 秒
        Long remainTime = redisTemplate.opsForValue().getOperations().getExpire(key);
//        if (remainTime <= 0 ){
//            return false;
//        }

        time = remainTime != null || remainTime >0 ? time + remainTime : time;
        log.debug("剩余过期时间{}s", time);
        // 更新过期时间
        Boolean expire = redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return expire;
    }


}
